import { login_by_pwd, is_login, to_logout, get_platform_user } from "api/auth";
import router, { asyncRouterMap, constantRouterMap } from '../../router';
import { getPermissions } from 'utils/permissions';

const user = {
	state: {
		store_token: localStorage.getItem('yh-admin-token'),
		store_info: localStorage.getItem('yh-admin-info'),
		store_permissions: [],
		store_elements: [],
		store_routers: constantRouterMap,
		store_add_routers: [],
		store_name: "",
		store_phone: ""
	},
	mutations: {
		SET_STORE_TOKEN: (state, store_token) => {
			state.store_token = store_token;
		},
		SET_STORE_INFO: (state, store_info) => {
			state.store_info = store_info;
		},
		SET_STORE_PERMISSIONS: (state, store_permissions) => {
			state.store_permissions = store_permissions;
		},
		SET_STORE_ELEMENTS: (state, store_elements) => {
			state.store_elements = store_elements;
		},
		SET_STORE_ROUTERS: (state, store_routers) => {
			state.store_add_routers = store_routers;
			state.store_routers = constantRouterMap.concat(store_routers);
		},
		SET_STORE_ADD_ROUTERS: (state, store_add_routers) => {
			state.store_add_routers = store_add_routers;
		},
		SET_STORE_NAME: (state, store_name) => {
			state.store_name = store_name;
		},
		SET_STORE_PHONE: (state, store_phone) => {
			state.store_phone = store_phone;
		}
	},
	actions: {
		/**
		 * ! 密码登录函数
		 */
		StoreLoginByPwd({ commit }, userInfo) {
			return new Promise((resolve, reject) => {
				login_by_pwd({ account: userInfo.account, password: userInfo.password }).then(response => {
					if (response.data.code == 0) {
						const data = response.data.data;
						localStorage.setItem('yh-admin-token', data.id);
						localStorage.setItem('yh-admin-info', JSON.stringify(data))
						commit('SET_STORE_TOKEN', data.id);
						commit('SET_STORE_INFO', JSON.stringify(data));
					} else {
						localStorage.setItem('yh-admin-token', '');
						localStorage.setItem('yh-admin-info', '')
						commit('SET_STORE_TOKEN', '');
						commit('SET_STORE_INFO', '');
					}
					resolve(response.data)
				}).catch(error => {
					console.log(error)
					reject(error);
				});
			});
		},

		/* 用户是否登陆 */
		isLogin({ commit }, id) {
			return new Promise((resolve, reject) => {
				is_login(id)
					.then(res => {
						resolve(res)
					}).catch(error => {
						reject(error)
					})
			})
		},

		/* 用户退出 */
		logout({ commit }, id) {
			return new Promise((resolve, reject) => {
				to_logout(id).then(res => {
					commit('SET_STORE_TOKEN', '');
					commit('SET_STORE_INFO', '');
					commit('SET_STORE_ROUTERS', constantRouterMap);
					commit('SET_STORE_PERMISSIONS', []);
					commit('SET_STORE_ELEMENTS', []);
					commit('SET_STORE_ADD_ROUTERS', []);

					localStorage.removeItem('yh-admin-token');
					localStorage.removeItem('yh-admin-info');
					router.push({
						path: '/login'
					});
					resolve()
				}).catch(error => {
					reject(error)
				})
			});
		},

		/* 获取用户信息 */
		StoreGetInfo({ commit, state }) {
			return new Promise((resolve, reject) => {
				let uId = localStorage.getItem('yh-admin-token');
				if (uId) {
					get_platform_user(uId).then(response => {
						let data = response.data.data;
						// console.log(response)
						commit('SET_STORE_NAME', data['name']);
						commit('SET_STORE_PHONE', data['phone']);

						let permissions = getPermissions();
						if (!permissions.length) {
							alert('您当前登录的账号没有任何系统操作权限,请联系管理员');
							reject(400);
						}
						// 						if(data.role === "super_admin") {
						// 							permissions.push({
						// 								"name": "DlSystem",
						// 								"text": "系统管理",
						// 								"submenus": [
						// 									{
						// 										"name": "DlSystemUser",
						// 										"text": "用户管理"
						// 									}
						// 								]
						// 							});
						// 						}
						commit('SET_STORE_PERMISSIONS', permissions);
						resolve(Object.assign(data, { permissions: permissions }));
					}).catch(error => {
						reject(error);
					});
				} else {
					reject(400);
				}
			});
		},
		/**
		 * ! 组装路由
		 */
		StoreGenerateRoutes({ commit }, data) {
			return new Promise(resolve => {
				const { permissions } = data;
				let elements = [];
				for (let menu of permissions) {
					if (menu.submenus) {
						for (let submenu of menu.submenus) {
							if (submenu.elements) {
								elements = elements.concat(submenu.elements.map(item => item.name));
							}
						}
					}
				}
				commit('SET_STORE_ELEMENTS', elements);
				const accessedRouters = asyncRouterMap.filter(v => {
					if (hasPermission(permissions, v)) {
						if (v.children && v.children.length > 0) {
							v.children = v.children.filter(child => {
								if (hasPermission(permissions, child)) {
									if (child.children && child.children.length > 0) {
										child.children = child.children.filter(_child => {
											if (hasPermission(permissions, _child)) {
												return _child
											}
										})
									}
									return child
								}
								return false;
							});
							return v
						} else {
							return v
						}
					}
					return false;
				});
				accessedRouters.forEach(item => {
					if (!item.redirect && item.children && item.children.length) {
						item.redirect = item.children[0]['path'];
					}
				});
				commit('SET_STORE_ROUTERS', accessedRouters.concat([{
					path: '*', // 页面不存在的情况下会跳到404页面
					redirect: '/error',
					name: 'notFound',
				},
				]));
				resolve();
			});
		},

	}
}
export default user;
/**
 *  ! 权限数据处理工具
 */
function hasPermission(permissions, route) {
	if (route.name) {
		for (let permission of permissions) {
			if (permission.name === route.name) return true;
			if (permission.submenus) {
				for (let submenu of permission.submenus) {
					if (submenu.name === route.name) return true;
				}
			}
		}
		return false;
	} else {
		return true;
	}
}